﻿if (typeof Modules == "undefined") Modules = {};
if (typeof Modules.Core == "undefined") Modules.Core = {};
//------------------------------------------------------------------------------
//Desctition: default variable
//------------------------------------------------------------------------------
Modules.Core.Default = {
    Input: 'vtnt-data-input',
    Type: 'vtnt-data-type',
    LayoutContent: '#content-main',
    Image: '../../images/no_image.jpg',
    ImageLoader: '../../images/loader.gif',
    TemplatePath: '../../asset/template/'
};
//------------------------------------------------------------------------------
//Create by: tantajnguyen@gmail.com
//Create date: 2014/03/26
//Desctition: custom core function
//------------------------------------------------------------------------------
Modules.Core.CoreFunction = {
    TemplateViewDefault: null,
    getTemplateView: function () {
        if (this.TemplateViewDefault == null) {
            var template = Modules.Core.QueryString.Template() || VTNT.Template || 'maxsport';
            this.TemplateViewDefault = Modules.Core.Default.TemplatePath + template;
        }
        return this.TemplateViewDefault;
    },
    getDataInput: function ($ctrl, prop) {
        prop = prop || Modules.Core.Default.Input;
        var ret = '';
        ret = $ctrl.attr(prop);
        if (typeof ret == 'undefined') {
            ret = '';
        }
        else {
            $ctrl.removeAttr(prop);
        }
        return ret;
    },
    getInputValue: function (input) {
        return '<' + input + '/>';
    }
};
function loadResourceById(type, id) {
    loadResource(type, '', id);
};
function loadResourceByCat(type, id) {
    loadResource(type, id);
};
function loadResource(type, catID, id) {
    Modules.Layout.Type = type;
    var obj = {};
    if (typeof catID != 'undefined') {
        obj.CatID = catID;
    }
    if (typeof id != 'undefined') {
        obj.ID = id;
    }
    if (!ObjectIsNullOrEmpty(obj) && typeof reloadResource == 'function') {
        reloadResource(obj);
    }
};
//------------------------------------------------------------------------------
//Create by: tantajnguyen@gmail.com
//Create date: 2014/03/26
//Desctition: load html detail
//------------------------------------------------------------------------------
Modules.Core.Cookie = {
    LanguageID: function (pValue) {
        var cookieName = "VTNT:LanguageID";
        if (pValue) {
            $.SetCookie(cookieName, pValue);
        }
        else {
            return $.GetCookie(cookieName) || "129";
        }
    }
};
Modules.Core.QueryString = {
    ID: function () {
        return $.GetURL("ID");
    },
    PID: function () {
        return $.GetURL("PID");
    },
    CatID: function () {
        return $.GetURL("CatID");
    },
    Type: function () {
        return $.GetURL("Type");
    },
    Template: function () {
        return $.GetURL("Template");
    },
    RowInPage: function () {
        return $.GetURL("ipage");
    },
    PageIndex: function () {
        return $.GetURL("page");
    }
};
Modules.Core.Service = {
    Get: function (pUrl, pOptions, pCallback) {
        if (typeof pOptions == "undefined") {
            return false;
        }
        var options = {
            RootName: "InputValue",
            LanguageID: Modules.Core.Cookie.LanguageID()
        };
        if ($.isArray(pOptions)) {
            pOptions.push({
                RootName: "InputValue",
                LanguageID: Modules.Core.Cookie.LanguageID()
            });
            options = pOptions;
        }
        else {
            $.extend(true, options, pOptions);
        }
        var inputValue = $.GetXmls(options);

        $.Ajax({
            url: pUrl,
            type: "POST",
            isServiceData: 1,
            data: {
                inputValue: $.HtmlEncode(inputValue)
            },
            success: function (data, textStatus, XMLHttpRequest) {
                if (data) {
                    data = $.FindInXml(data);
                    if (data) {
                        data = data.CSV2JSON2();
                    }
                }
                if (typeof pCallback == "function") {
                    pCallback(data);
                }
            }
        });
    },
    GetResource: function (pOptions, pCallback) {
        this.Get('Core/CoreService.asmx/GetResource', pOptions, pCallback);
    },
    GetContextData: function (pOptions, pCallback) {
        this.Get('Core/CoreService.asmx/GetContextData', pOptions, pCallback);
    }
};
//------------------------------------------------------------------------------
//Create by: dolamthien@gmail.com
//Create date: 2014/03/05
//------------------------------------------------------------------------------
Modules.ServiceData = {
    Get: function (pUrl, pInputValue, pCallback) {
        $.Ajax({
            url: pUrl,
            type: "POST",
            isServiceData: 1,
            data: {
                inputValue: $.HtmlEncode(pInputValue)
            },
            success: function (data, textStatus, XMLHttpRequest) {
                if (data) {
                    data = $.FindInXml(data);
                    if (data) {
                        data = data.CSV2JSON2();
                    }
                }
                if (typeof pCallback == "function") {
                    pCallback(data);
                }
            }
        });
    },
    GetContextData: function (pInputValue, pCallback) {
        //dlt
        //inputCore: Chỗ này sẽ quản lý ngôn ngữ đang dùng để truyền vào & các tham số core khác
        var inputCore = '<InputValue LanguageID="129" />';

        pInputValue = inputCore + pInputValue;
        this.Get('Core/CoreService.asmx/GetContextData', pInputValue, pCallback);
    }
};
//------------------------------------------------------------------------------
//Create by: tantajnguyen@gmail.com
//Create date: 2014/03/26
//Desctition: load html detail
//------------------------------------------------------------------------------
Modules.Core.View = {
    init: function ($el, data) {
        var tagName = $el.get(0).tagName;
        switch (tagName) {
            case 'DIV':
                this.showDiv($el, data);
                break;

            case 'UL':
            case 'OL':
                this.showUl($el, data);
                break;
        }
    },
    showDiv: function ($el, data) {
        data = data[0];
        if (data) {
            var html = $el.html();
            if (html.length) {
                $el.html(this.getReplace(html, data));
            }
            else {
                $el.html(data.Detail || data.Summary);
            }
        }
    },
    showUl: function ($el, data) {
        var template = $el.html(),
            level = '0',
            $ul = $('<ul></ul>'),
            $lastUl;

        $el.html('');
        for (var i = 0; i < data.length; i++) {
            var it = data[i];
            var sli = this.getReplace(template, it);

            if (it.Level > 1) {
                if (level == '0' || level < it.Level) {
                    $lastUl = $ul.clone();
                    $lastUl.append(sli);

                    $el.find('li[level="' + level + '"]:last-child').append($lastUl);
                }
                else if (level == it.Level) {
                    if ($lastUl == null) {
                        $el.find('li[level="' + level + '"]:last-child').after(sli);
                    }
                    else {
                        $lastUl.append(sli);
                    }
                }
                else {
                    $lastUl.parent().after(sli);
                    $lastUl = null;
                }
            }
            else {
                $el.append(sli);
            }
            level = it.Level;
        }
        var type = $el.attr(Modules.Core.Default.Type);
        if (typeof type != 'undefined') {
            switch (type) {
                case 'slider':
                    this.initSlider($el);
                    break;

                case 'image':
                    this.initImage($el);
                    break;
            }
            $el.removeAttr(Modules.Core.Default.Type);
        }
    },
    initImage: function ($el) {
        $el.find('img').unveil(100, function () {
            $(this).removeAttr('data-src');
        });
    },
    initSlider: function ($el) {
        window.setTimeout(function () {
            Modules.Core.View.initImage($el);

            $.getScript('../../asset/js/jq/plugin/flexslider/jquery.flexslider.js', function () {
                $el.parent().flexslider({
                    animation: "fade",              //String: Select your animation type, "fade" or "slide"
                    slideDirection: "horizontal",   //String: Select the sliding direction, "horizontal" or "vertical"
                    slideshow: true,                //Boolean: Animate slider automatically
                    slideshowSpeed: 5000,           //Integer: Set the speed of the slideshow cycling, in milliseconds
                    animationDuration: 500,         //Integer: Set the speed of animations, in milliseconds
                    directionNav: false,             //Boolean: Create navigation for previous/next navigation? (true/false)
                    controlNav: true,               //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
                    keyboardNav: true,              //Boolean: Allow slider navigating via keyboard left/right keys
                    mousewheel: false,              //Boolean: Allow slider navigating via mousewheel
                    prevText: "Previous",           //String: Set the text for the "previous" directionNav item
                    nextText: "Next",               //String: Set the text for the "next" directionNav item
                    pausePlay: false,               //Boolean: Create pause/play dynamic element
                    pauseText: 'Pause',             //String: Set the text for the "pause" pausePlay item
                    playText: 'Play',               //String: Set the text for the "play" pausePlay item
                    randomize: false,               //Boolean: Randomize slide order
                    slideToStart: 0,                //Integer: The slide that the slider should start on. Array notation (0 = first slide)
                    animationLoop: true,            //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
                    pauseOnAction: true,            //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
                    pauseOnHover: false,            //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
                    controlsContainer: ".slide-container",          //Selector: Declare which container the navigation elements should be appended too. Default container is the flexSlider element. Example use would be ".flexslider-container", "#container", etc. If the given element is not found, the default action will be taken.
                    start: function () { },            //Callback: function(slider) - Fires when the slider loads the first slide
                    before: function () { },           //Callback: function(slider) - Fires asynchronously with each slider animation
                    after: function () { },            //Callback: function(slider) - Fires after each slider animation completes
                    end: function () { }               //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
                });
            });
        }, 100);
    },
    getReplace: function (temp, obj) {
        var aReplaceName = ['[LinkUrl]', '[Name]', '[Image]', '[Detail]', '[Summary]', '[IDKey]', '[ParentKey]', '[ActionLink]', '[Home]', '[Level]', '[Video]'],
            s = temp;
        for (var i = 0; i < aReplaceName.length; i++) {
            if (s.indexOf(aReplaceName[i]) > 0) {
                s = this.getReplaceValue(s, aReplaceName[i], obj);
            }
        }
        return s;
    },
    getReplaceValue: function (text, name, obj) {
        var ret = text, value = '';
        var relName = name.replace(/\[|\]/gi, '');
        switch (relName) {
            case 'LinkUrl':
                value = obj.LinkURL || 'javascript:void(0);';
                break;

            case 'Name':
                value = obj.Name || obj.Code;
                break;

            case 'Detail':
                value = obj.Detail;
                break;

            case 'Summary':
                value = obj.Summary;
                break;

            case 'Image':
                value = obj.Image || Modules.Core.Default.Image;
                break;

            case 'IDKey':
                value = obj.IDKey;
                break;

            case 'ParentKey':
                value = obj.ParentKey;
                break;

            case 'ActionLink':
                value = Modules.Layout.actionLink();
                break;

            case 'Home':
                value = Modules.Layout.homeLink();
                break;

            case 'Level':
                value = obj.Level;
                break;

            case 'Video':
                var vid = $.GetURL("v", "", obj.LinkURL);
                value = vid;
                break;
        }
        ret = text.split(name).join(value);

        return ret;
    }
};
//------------------------------------------------------------------------------